#include <boost/bind.hpp>
#include <boost/asio.hpp>


#include "TCPServer.h"

#include "Config.h"
#include "Common.h"


namespace RisingStar
{
	CTCPServer::CTCPServer(WORD port)://mServicePtr(new asio::io_service()),
					mServices(CONF_MIN_TASK_COUNT,CONF_MAX_TASK_COUNT),
			
							mAcceptor(*mServices.GetServicePtr(), ip::tcp::endpoint(ip::tcp::v4(), port))
	{
		CreateNewSession();

	}
	CTCPServer::~CTCPServer()
	{

	}
    void CTCPServer::HandleAccept(CTCPSession* newSession, const boost::system::error_code& error)
    {
		
        if (!error)
        {
			cout<<"接收到请求"<<endl;
			//新的请求开始
            newSession->Start();
        }
        else
        {
			cout<<"session创建过程中发生了错误"<<endl;
            delete newSession;
        }

		CreateNewSession();
    }
	
	bool CTCPServer::CreateNewSession()
	{
		//将第一个服务赋值给session
		_EVENT("创建一个会话");
		
		CTCPSession* newSession = new CTCPSession(/*service*/mServices.GetServicePtr());

        mAcceptor.async_accept(newSession->GetSocket(),
            boost::bind(&CTCPServer::HandleAccept, this, newSession, asio::placeholders::error));
	}
	
	void CTCPServer::Run()
    {
		//ThreadPtr pThread(new boost::thread(bind(&asio::io_service::run, &m_io)));
        //mServices.Start();

		boost::function0<void> f = boost::bind(&CTCPServer::ServicesProcess, this);
        boost::thread thrd(f);  
		
        mServices.Join();
    }
	
	//服务管理
	void CTCPServer::ServicesProcess()
	{
		while(1)
		{
			mServices.ProcessFreeService();

			//一分钟检测一次
			sleep(10);
		}
		
	}
}